package com.graduation.cdm.funactivity.view;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.graduation.cdm.funactivity.MainActivity;
import com.graduation.cdm.funactivity.MyApplication;
import com.graduation.cdm.funactivity.R;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

import static com.graduation.cdm.funactivity.util.GlobalConstant.preUrl;
import static com.graduation.cdm.funactivity.util.GlobalConstant.userId;

public class LoginActivity extends AppCompatActivity {

    @InjectView(R.id.iv_bank)
    ImageView ivBank;
    @InjectView(R.id.ttop)
    RelativeLayout ttop;
    @InjectView(R.id.iv_name)
    ImageView ivName;
    @InjectView(R.id.user_name)
    EditText userName;
    @InjectView(R.id.iv_psd)
    ImageView ivPsd;
    @InjectView(R.id.user_psw)
    EditText userPsw;
    @InjectView(R.id.user_login)
    Button userLogin;
    @InjectView(R.id.user_add)
    TextView userAdd;
    @InjectView(R.id.activity_login)
    LinearLayout activityLogin;

    String loginName;
    String password;
    Boolean isLogin = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.inject(this);

        SharedPreferences sharedPreferences = getSharedPreferences("user_info",MODE_PRIVATE);
        loginName = sharedPreferences.getString("userName","");
        password = sharedPreferences.getString("userPassword","");
        isLogin = sharedPreferences.getBoolean("isLogin",false);
        if (loginName != "" && password != "" && isLogin){
            Intent intent = new Intent(getApplicationContext(),MainActivity.class);
            startActivity(intent);
            finish();
        }

    }

    @OnClick({R.id.iv_bank, R.id.user_login, R.id.user_add})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_bank:
                finish();
                break;
            case R.id.user_login:
                loginName = userName.getText().toString();
                password = userPsw.getText().toString();
                loginRequest();
                break;
            case R.id.user_add:
                Intent intent = new Intent(getApplicationContext(),RegisteActivity.class);
                startActivity(intent);
                break;
        }
    }

    private void loginRequest(){
        String url = preUrl +"user/login";
        StringRequest loginRequest =new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                System.out.println("=="+s.trim());
                try {
                    JSONObject jsonObject = new JSONObject(s);
                    System.out.println("===+"+jsonObject.get("result"));
                    JSONObject userObject = jsonObject.getJSONObject("user");
                    if (jsonObject.get("result").equals("sucess")) {
                        SharedPreferences sharedPreferences = getSharedPreferences("user_info",MODE_PRIVATE);
                        SharedPreferences.Editor editor = sharedPreferences.edit();
                        editor.putInt("userId",userObject.getInt("userId"));
                        editor.putString("userName",userObject.getString("userName"));
                        editor.putString("userPassword",userObject.getString("userPassword"));
                        editor.putString("userSex",userObject.getString("userSex"));
                        editor.putString("userPhone",userObject.getString("userPhone"));
                        editor.putString("userEmail",userObject.getString("userEmail"));
                        editor.putString("imgUrl",userObject.getString("imageUrl"));
                        editor.putBoolean("isLogin",true);
                        editor.commit();
                        userId=userObject.getInt("userId");

                        Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                        startActivity(intent);
                        finish();
                    }else {
                        Toast.makeText(getApplicationContext(),"服务器出错！",Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    System.out.println("ffffffffff"+e.toString());
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                System.out.println("xxxxxxxxxxxxx："+volleyError.toString());
            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> map=new HashMap<>();
                map.put("userName",loginName);
                map.put("password",password);
                return map;
            }
        };
        MyApplication.getRequestQueue().add(loginRequest);
    }

    /*private long firstTime = 0;
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            long secondTime = System.currentTimeMillis();
            if (secondTime - firstTime > 2000) {
                Toast.makeText(LoginActivity.this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                firstTime = secondTime;
                return true;
            } else {
                System.exit(0);
            }
        }
        return super.onKeyDown(keyCode, event);
    }*/
}